from django.shortcuts import render, HttpResponse

from .models import Question
import os
# from django.conf import Settings  # 内置的settings
from newlife import settings

from django.views import View


# Create your views here.

def index(request):
    return HttpResponse('kkkkkkk')


def add_question(request):
    # 展示收集界面
    if request.method == "GET":
        return render(request, 'add_question.html')

    # 接收前台传递过来的数据  保存到数据库
    if request.method == "POST":
        title = request.POST.get('title')
        qtype = request.POST.get('qtype')
        option1 = request.POST.get('option1')
        option2 = request.POST.get('option2')
        option3 = request.POST.get('option3')
        option4 = request.POST.get('option4')
        ref_answer = request.POST.get('ref_answer')
        analysis = request.POST.get('analysis')

        q1 = Question(
            title=title,
            qtype=qtype,
            option1=option1,
            option2=option2,
            option3=option3,
            option4=option4,
            ref_answer=ref_answer,
            analysis=analysis
        )
        q1.save()
        result = "插入成功"
        return render(request, 'add_question.html', {"result": result})


def query_question(request):
    if request.method == "GET":
        questions = []
        return render(request, 'query_question.html', {"questions": questions})

    if request.method == "POST":
        wd = request.POST.get("wd")
        print(wd)

        # queryset中很多方法可以链式调用
        # questions = Question.objects.filter(title__contains='明显').filter(title__contains='客户')
        questions = Question.objects.filter(title__contains=wd)
        # questions = Question.objects.
        print(type(questions))
        print(questions)

        return render(request, 'query_question.html', {"questions": questions})


import os


def save_icon(iconfile):
    """
    将获取到的icon保存到本地
    :return: 图片的路径
    """
    # img_path = r'/static/img/'
    # img_path_all = img_path + iconfile.name
    # img_path_all2 = '..' + img_path + iconfile.name
    imgname = iconfile.name
    filename = os.path.join(settings.BASE_DIR, 'static/img/', imgname)
    print(filename)
    with open(filename, 'wb') as f:
        for chunk in iconfile.chunks():
            f.write(chunk)
    return '/static/img/' + imgname


from .models import Student


def exam(request):
    if request.method == "GET":
        return render(request, 'exam.html', {"r": 4})

    name = request.POST.get("name", "")
    sex = request.POST.get("sex", "")
    cls = request.POST.get("cls", "")
    subject = request.POST.get("subject", "")
    icon = request.FILES.get("icon")

    # print(settings.BASE_DIR)
    img_path = save_icon(icon)
    print(img_path)
    s = Student(stu_name=name, sex=sex, cls=cls, subject=subject, img_path=img_path)
    s.save()

    return HttpResponse("一切ok!")


from .models import Score


def score(request):
    if request.method == "GET":
        return render(request, 'score.html')

    name = request.POST.get("name", "")
    blanks = request.POST.get("blanks", "")
    quers = request.POST.get("quers", "")
    comput = request.POST.get("comput", "")
    showok = request.POST.get("showok")

    s = Score(
        name=name,
        blanks=blanks,
        quers=quers,
        comput=comput,
        showok=showok,
    )

    s.save()
    return HttpResponse("ok")


from django.core.paginator import Paginator


# def stuList(request):
def stu_list(request):
    students = Student.objects.all()
    per_page = 3
    paginator = Paginator(students, per_page)
    max_page = paginator.num_pages
    # print(max_page,'--------')
    # page 页码 存在于url的参数中  路径?page=x123
    x = request.GET.get('page', 1)

    try:
        x = int(x)
        if x < 1:
            x = 1
        if x > max_page:
            x = max_page
    except:
        x = 1

    # pagex 是一个page对象, 不是list,也不能像list 容器一样使用
    pagex = paginator.get_page(x)
    # 第x页的学生
    students_pagex = pagex.object_list

    # if x == max_page:
    #     has_next = False
    # else:
    #     has_next = True
    # hasnot_next = x == max_page
    has_next = pagex.has_next()
    # return render(request, 'stu_list.html', {"students": students_pagex, 'current_page': x, 'max_page': max_page})
    # return render(request, 'stu_list.html', {"students": students_pagex, 'current_page': x, 'has_next': not hasnot_next})
    return render(request, 'stu_list.html', {"students": students_pagex, 'current_page': x, 'has_next': has_next})


def stu_del(request):
    stu_id = request.GET.get('id', '')
    Student.objects.get(id=stu_id).delete()
    return HttpResponse("删除成功!")


def stu_get(request):
    stu_id = request.GET.get('id', '')
    stu = Student.objects.get(id=stu_id)

    return render(request, 'stu_info.html', {"stu": stu})


from .models import Scoreexam


def collectscore(request):
    if request.method == "GET":
        return render(request, 'collectscore.html')

    name = request.POST.get("name", "")
    blanks = request.POST.get("blanks", "0")
    quers = request.POST.get("quers", "0")
    choiceq = request.POST.get("choiceq", "0")
    comput = request.POST.get("comput", "0")
    showok = request.POST.get("showok")

    s = Scoreexam(
        name=name,
        blanks=blanks,
        quers=quers,
        choiceq=choiceq,
        comput=comput,
        showok=showok,
    )
    s.save()
    return HttpResponse("收到!")


# from .myforms import StudentForm
#
# def mystudent(request):
#     if request.method=='GET':
#         form = StudentForm()
#         return render(request,'mystudent.html',{"form":form})
#     else:
#         form = StudentForm(request.POST)
#         if form.is_valid():  # 进行数据校验
#             # 校验成功
#             data = form.cleaned_data  # 校验成功的值，会放在cleaned_data里。
#             print(data)
#             print(type(data))
#
#             return HttpResponse(
#                 'ok'
#             )
# return render(request, "xx.html", {"form": form})
# else:
#     print(form.errors)  # 打印错误信息
#     clean_errors = form.errors.get("__all__")
#     print(222, clean_errors)
# return render(request, "xxx.html", {"form": form, "clean_errors": clean_errors})

from .myforms import TeacherForm
from .models import Teacher


def teacher(request):
    if request.method == "GET":
        teacher_form = TeacherForm()
        return render(request, 'teacher.html', {'teacher_form': teacher_form})

    if request.method == "POST":
        teacher_form = TeacherForm(request.POST)
        # print(teacher_form)
        # print(type(teacher_form))

        # name = request.POST.get('name','')
        # if len(name)<10
        # 校验 表单 各个字段是否合法
        if teacher_form.is_valid():
            data = teacher_form.cleaned_data
            # print(data)
            # print(type(data))
            t = Teacher2(**data)
            t.save()

        return HttpResponse('ok')


class Teacher1(View):
    def get(self, request):
        teacher_form = TeacherForm()
        # raise Exception("kkk")
        return render(request, 'teacher.html', {'teacher_form': teacher_form})

    def post(self, request):
        teacher_form = TeacherForm(request.POST)

        if teacher_form.is_valid():
            data = teacher_form.cleaned_data

            t = Teacher2(**data)
            t.save()

        return HttpResponse('ok')


from django.template.response import TemplateResponse


def index1(request):
    print("这里是 index 页面")
    rep = TemplateResponse("这里是主页面 index", 'exam.html')

    # def render():
    #     print("这里是 index 函数里的 render 方法")
    #     return HttpResponse("index")
    #
    # rep.render = render()
    return rep


#
from django.views import View


class Teacher2(View):

    def get(self, request):
        print('----', id(request))
        # raise Exception('异常了')
        teacher_form = TeacherForm()
        return render(request, 'teacher.html', {"teacher_form": teacher_form})

    def post(self, request):
        teacher_form = TeacherForm(request.POST)

        if teacher_form.is_valid():
            data = teacher_form.cleaned_data

            t = Teacher(**data)
            t.save()

        return HttpResponse('ok')


from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, user_logged_out
